﻿using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using Microsoft.WindowsAPICodePack.Dialogs;
using System.IO;
using System.Drawing;
using System.Runtime.InteropServices;

namespace thread_WPF
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();
		}
		[DllImport("User32.dll", EntryPoint = "SendMessage")]
		private static extern int SendMessage(
		IntPtr hWnd, // handle to destination window
		int Msg, // message
		int wParam, // first message parameter
		int lParam // second message parameter
		);
		[DllImport("kernel32.dll")]
		static extern int GetTickCount();

		static Random rand = new Random();
		private Semaphore full;
		private Semaphore empty;
		private Mutex mutex;
		private Queue<int> queue = new Queue<int>();
		private bool running = false;
		private string folder;

		//用于显示信息
		private delegate void appendDelegate(string comment);
		private void appendResult(string sentence)
		{
			if (!Out.Dispatcher.CheckAccess())
			{
				//声明，并实例化回调
				appendDelegate append = appendResult;
				//使用回调
				Out.Dispatcher.Invoke(append, sentence);
			}
			else
			{
				Out.Text += "\n\t" + sentence;
			}
		}
		


		private void ProduceStart_Click(object sender, RoutedEventArgs e)
		{
			if (running == false)
			{
				running = true;
				ProduceStart.Content = "停止活动";
				Out.Text = "";
				queue.Clear();
				mutex = new Mutex();
				full = new Semaphore(0, 10);
				empty = new Semaphore(10, 10);
				int producerNum = int.Parse(tb1.Text);
				int consumerNum = int.Parse(tb2.Text);
				for (int i = 1; i <= producerNum; i++)
				{
					Thread temp = new Thread(new ParameterizedThreadStart(ProducerRun));
					temp.IsBackground = true;
					temp.Start(i);
				}
				for (int i = 1; i <= consumerNum; i++)
				{
					Thread temp = new Thread(new ParameterizedThreadStart(ConsumerRun));
					temp.IsBackground = true;
					temp.Start(i);
				}
			}
			else
			{
				running = false;
				ProduceStart.Content = "开始活动";
				appendResult("活动已停止");
			}
		}

		private void ProducerRun(object id)
		{
			while (running)
			{
				empty.WaitOne();
				mutex.WaitOne();
				int num = (int)id * 100 + rand.Next(100);
				queue.Enqueue(num);
				appendResult(id + "号生产者：生产了" + num);
				mutex.ReleaseMutex();
				full.Release();
				Thread.Sleep(rand.Next(2000));
			}
		}
		private void ConsumerRun(object id)
		{
			while (running)
			{
				full.WaitOne();
				mutex.WaitOne();
				int num = queue.Dequeue();
				appendResult(id + "号消费者：消费了" + num);
				mutex.ReleaseMutex();
				empty.Release();
				Thread.Sleep(rand.Next(2000));
			}
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			if (!running)
			{

				var dlg = new CommonOpenFileDialog();
				dlg.IsFolderPicker = true;
				//dlg.InitialDirectory = currentDirectory;

				if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
				{
					folder = dlg.FileName;
				}
				appendResult("监听文件夹及截图保存文件夹均设置为" + folder);
			}
		}
		public static IntPtr WINDOW_HANDLER;
		public static ManualResetEvent e_wdirth_end = new ManualResetEvent(false);

		public const int WM_USER = 0x400;
		public const int WATCH_FILE = WM_USER + 0x200;
		public const int CAPTURE_FILE = WM_USER + 0x201;
		public const int CAPTURE_FOLDER = WM_USER + 0x202;
		static ManualResetEvent capture_terminate_e;     //结束抓屏线程事件 
		static ManualResetEvent capture_this_one_e;      //抓屏事件
		public static ManualResetEvent[] me_cap = new ManualResetEvent[2];

		public static string strfileCapture;
		public static string strfolderCapture;
		private void Capture_screen(object obj)
		{
			int s_wid = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
			int s_height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
			Bitmap b_1 = new Bitmap(s_wid, s_height);
			Graphics g_ = Graphics.FromImage(b_1);
			String init_dir_fn = folder;
			String dest_fn = null;

			//用事件的方法来抓获图片 
			int index = WaitHandle.WaitAny(me_cap, 500);
			while (index != 0)
			{
				if (index == 1)
				{
					dest_fn = init_dir_fn;
					dest_fn += "\\Screenshots\\";
					if (!Directory.Exists(dest_fn))
					{
						Directory.CreateDirectory(dest_fn);
					}
					strfolderCapture = dest_fn;
					//                    parent.showPath(strfolderCapture);
					SendMessage(WINDOW_HANDLER, CAPTURE_FOLDER, 0, 0);

					string fileName = GetTickCount().ToString();
					fileName += "ab.bmp";
					dest_fn += fileName;

					strfileCapture = fileName;
					SendMessage(WINDOW_HANDLER, CAPTURE_FILE, 0, 0);

					g_.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(s_wid, s_height));
					b_1.Save(dest_fn, System.Drawing.Imaging.ImageFormat.Bmp);
					capture_this_one_e.Reset();
				}
				index = WaitHandle.WaitAny(me_cap, 500);
			}
			g_.Dispose();
			b_1.Dispose();
		}
		private void Button_Click_1(object sender, RoutedEventArgs e)
		{
			//初始抓屏终止事件为未结束 
			capture_terminate_e = new ManualResetEvent(false);
			//初始捕获终止状态为未结束 
			capture_this_one_e = new ManualResetEvent(false);
			//启动捕捉线程
			me_cap[0] = capture_terminate_e;
			me_cap[1] = capture_this_one_e;
			ParameterizedThreadStart workStart = new ParameterizedThreadStart(Capture_screen);
			Thread workThread = new Thread(workStart);
			workThread.IsBackground = true;
			workThread.Start(this);
			appendResult("截图线程已启动");
		}

		private void Button_Click_2(object sender, RoutedEventArgs e)
		{
			capture_this_one_e.Set();
            appendResult("已截图");
        }

		private void Button_Click_3(object sender, RoutedEventArgs e)
		{
            capture_terminate_e.Set();
            appendResult("截图线程已结束");
        }

        private void WatchDir()
        {
            long now_t = DateTime.Now.ToFileTime();
            DirectoryInfo d_info = new DirectoryInfo(folder);
            string new_filename;
            FileInfo[] f_ins = d_info.GetFiles();

            //e_wdirth_end有信号，为true，则不用阻塞等待，
            //e_wdirth_end无信号，为false，则需要阻塞等待
            while (!e_wdirth_end.WaitOne(500))   //
            {
                for (int i = 0; i < f_ins.Length; i++)
                {
                    now_t = DateTime.Now.ToFileTime();
                    if (File.Exists(f_ins[i].FullName))
                    {
                        appendResult("监视到文件" + f_ins[i].FullName);
                        if (WINDOW_HANDLER != IntPtr.Zero)
                            SendMessage(WINDOW_HANDLER, WATCH_FILE, 0, 0);
                        string newDir = folder + "\\Collection\\";
                        if (!Directory.Exists(newDir))
                        {
                            Directory.CreateDirectory(newDir);
                        }

                        new_filename = newDir + now_t.ToString() + f_ins[i].Name;
                        if (!File.Exists(new_filename))
                        {
                            File.Move(f_ins[i].FullName, new_filename);
                        }
                    }
                }
                f_ins = d_info.GetFiles();//重新获取新的目录信息
            }
        }

		private void Button_Click_4(object sender, RoutedEventArgs e)
		{
            e_wdirth_end.Reset();
            Thread workThread = new Thread(new ThreadStart(WatchDir));
            workThread.IsBackground = true;
            workThread.Start();
        }

		private void Button_Click_5(object sender, RoutedEventArgs e)
		{
            e_wdirth_end.Set();
        }
	}
}
